//
//  WEXComposeView.swift
//  microBlog
//
//  Created by apple on 16/4/25.
//  Copyright © 2016年 Hill. All rights reserved.
//

import UIKit
import pop

class WEXComposeView: UIView {
    
    
    // 快速初始化按钮数组
    lazy var menuButton: [WEXComposeMenuButton] = []
    
    // 模型数组
    lazy var array: [WEXComposeMenuItemInfoModel] = {
        
        return self.buttonInfo()
        
    }()
    
    // 属性，供类使用
    var target: UIViewController?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // 设置ui界面
    private func setupUI() {
        
        frame = UIScreen.mainScreen().bounds
        
//        设置一张毛玻璃图片
        let image = UIImage.getScreenShot().applyLightEffect()
        
        let imageView = UIImageView(image: image)
//        添加毛玻璃背景图
        addSubview(imageView)
    
        addSubview(igv_sologan)
        
//        添加sologan图标的约束
        igv_sologan.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self)
            make.top.equalTo(100)
            
        }
        
        addMenuButton()
        
    }
    
    override func didMoveToSuperview() {
         super.didMoveToSuperview()
        
        for (index,value) in menuButton.enumerate() {
            
            animation(value, index: index, isUp: true)
            
            
        }
    }
    
    // 从plist文件中读取数据
    private func buttonInfo() -> [WEXComposeMenuItemInfoModel] {
        // 获取存储文件路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        let array = NSArray(contentsOfFile: path)!
        
        var tempArray: [WEXComposeMenuItemInfoModel] = []
        
        for value in array {
            
            let info = WEXComposeMenuItemInfoModel(dict: value as! [String: AnyObject])
            
            tempArray.append(info)
        }
        
        return tempArray
        

        
    }
    // 执行动画
    func animation(value: UIView, index: Int, isUp: Bool) {
//        初始化动画对象，此动画为弹簧的动画
        let anima = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        anima.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + (isUp ? -350 : 350)))
        
        anima.springSpeed = 10
        anima.springBounciness = 8
//        设置按钮弹起的时间
        anima.beginTime = Double(index) * 0.025 + CACurrentMediaTime()
        
        value.pop_addAnimation(anima, forKey: nil)
        
    }
    
    
    
    // 添加按钮
    private func addMenuButton() {
        
        //设置按钮的宽高
        let itemH: CGFloat = 110
        let itemW: CGFloat = 80
        let margin: CGFloat = (SCREENWIDTH - 3 * itemW) / 4
        
        for (i,value) in array.enumerate() {
            
            let button = WEXComposeMenuButton(textColor: UIColor.blackColor(), textFont: 14)
            
            button.addTarget(self, action: "menuButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            button.tag = i
            
            button.setTitle(value.title, forState: UIControlState.Normal)
           
            button.setImage(UIImage(named: value.icon!), forState: UIControlState.Normal)
            
            button.frame.size = CGSize(width: itemW, height: itemH)
            
            addSubview(button)
            
            menuButton.append(button)
//            获取行和列索引
            let col = i % 3
            let row = i / 3
            
//            设置按钮的y值
            button.frame.origin.x = CGFloat(col) * itemW + CGFloat(col + 1) * margin
            button.frame.origin.y = CGFloat(row) * itemH + CGFloat(row) * 10 + SCREENHEIGHT
            
            
            
        }
        
    }
    
    // 重写touchBegan方法
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        super.touchesBegan(touches, withEvent: event)
        for (index,value) in menuButton.reverse().enumerate() {
            
            animation(value, index: index, isUp: false)
            
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.removeFromSuperview()
        }

        
    }

    // MARK: - 给外界传入控制器用
    func show(targetController: UIViewController?) {

        // 给目标控制器添加界面
        targetController?.view.addSubview(self)
        
        self.target = targetController
        
    }
    
    // MARK: - 点击按钮的事件
    @objc private func menuButtonClick(button: UIButton) {
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            
            for value in self.menuButton {
                
                value.alpha = 0.01
            
//                判断是否是当前button
                if value == button {
//                    是当前按钮，放大
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
//                    不是当前按钮，缩小
                    value.transform = CGAffineTransformMakeScale(0.01, 0.01)
                }
        
            }
            
            
            }) { (_) -> Void in
                
                let model = self.array[button.tag]
//                获取当前按钮需要推出的控制器
                let type = NSClassFromString(model.className!)! as! UIViewController.Type
//                实例化控制器
                let vc = type.init()
                
                self.target?.presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: { () -> Void in
//                    将View从父控件中移除
                    self.removeFromSuperview()
                })
                
                
        }
    }
    
    // MARK: - 懒加载子控件
    private lazy var igv_sologan = UIImageView(image: UIImage(named: "compose_slogan"))
    
    
    
}


